package cn.wps.moffice.main.local.filebrowser.logic;

import android.os.Handler;
import android.os.HandlerThread;
import cn.wps.moffice.main.local.filebrowser.operator.seek.IFinder.SeekType;

/**
 * 搜索后的回调，为了避免获取列表及排序导致界面卡住，单独启动一个线程
 */
public class SeekCallbackThread
{
	private static final String THREAD_NAME = "SeekCallbackThread";
	
	public interface Callback
	{
		public void refresh(SeekType seekType, int dirtyFlag, boolean isFinished);
	}
	
	/**
	 * SeekType
	 */
	private SeekType mSeekType;
	
	/**
	 * 脏标记
	 */
	int mDirtyFlag;
	
	/**
	 * 是否结束
	 */
	boolean mIsFinished;
	
	/**
	 * 线程执行的方法
	 */
	private Callback mCallback;
	
	/**
	 * Handler
	 */
	private Handler mHandler;
	
	/**
	 * HandlerThread
	 */
	private HandlerThread mHandlerThread;
	
	public SeekCallbackThread(Callback callback)
	{
		this.mCallback = callback;
	}
	
	public void dispose()
	{
		if (mHandler != null)
		{
			mHandler.removeCallbacks(mRunnable);
			mHandlerThread.quit();
			mHandler = null;
		}
	}
	
	public void refresh(SeekType seekType, int dirtyFlag, boolean isFinished)
	{
		if (mHandler == null)
		{
			mHandlerThread = new HandlerThread(THREAD_NAME);
			mHandlerThread.start();
			mHandler = new Handler(mHandlerThread.getLooper());
		}
		
		this.mSeekType = seekType;
		this.mIsFinished = isFinished;
		
		setDirtyFlag(dirtyFlag);
		
		mHandler.removeCallbacks(mRunnable);
		mHandler.post(mRunnable);
	}
	
	private synchronized void setDirtyFlag(int flag)
	{
		mDirtyFlag |= flag;
	}
	
	private synchronized int getDirtyFlagAndClear()
	{
		int flag = mDirtyFlag;
		mDirtyFlag = 0;
		return flag;
	}
	
	public boolean isFinished()
	{
		return mIsFinished;
	}
	
	private Runnable mRunnable = new Runnable()
	{
		@Override
		public void run()
		{
			int dirtyFlag = getDirtyFlagAndClear();
			mCallback.refresh(mSeekType, dirtyFlag, mIsFinished);
		}
	};
}
